//
//  MCTabBarController.m
//  MCTabBarDemo
//
//  Created by chh on 2017/12/4.
//  Copyright © 2017年 Mr.C. All rights reserved.
//

#import "MCTabBarController.h"
#import "MCTabBar.h"

#import "MainViewController.h"
#import "HuoYuanViewController.h"
#import "MyViewController.h"
#import "XPRootNavigationController.h"


#import "NYSTipsView.h"
#define AlertDuration MAXFLOAT

#import "CarTeamAuthVC.h"
#import "DriverAuthVC.h"
#import "SiJiManageViewController.h"
#import "VehicleListViewController.h"

@interface MCTabBarController ()<UITabBarControllerDelegate>
@property (nonatomic, strong) MCTabBar *mcTabbar;
@property (nonatomic, assign) NSUInteger selectItem;//选中的item
@property (nonatomic, strong) UIViewController *currentVC;
// 弹框关闭状态
@property (nonatomic, assign) BOOL isCloseAlert1;
@property (nonatomic, assign) BOOL isCloseAlert2;
@property (nonatomic, assign) BOOL isCloseAlert3;
@end

@implementation MCTabBarController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self alertTipsView];
}
//
- (void)viewDidLoad {
    [super viewDidLoad];
    
//    _mcTabbar = [[MCTabBar alloc] init];
//     [_mcTabbar.centerBtn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
//    //选中时的颜色
//    _mcTabbar.tintColor = [UIColor cy_colorWithHexString:@"#FF5545"];
////    [[UITabBarItem appearance] setTitleTextAttributes:@{ UITextAttributeTextColor : [UIColor blackColor], UITextAttributeFont:[UIFont fontWithName:@"Marion-Italic" size:12.0]}            forState:UIControlStateNormal];
//   //透明设置为NO，显示白色，view的高度到tabbar顶部截止，YES的话到底部
//    _mcTabbar.translucent = NO;
//    //利用KVC 将自己的tabbar赋给系统tabBar
//    [self setValue:_mcTabbar forKeyPath:@"tabBar"];
    [KNotificationCenter addObserver:self selector:@selector(logoutEvent) name:LOGIN_LOGOUT object:nil];
    [KNotificationCenter addObserver:self selector:@selector(alertTipsView) name:LOGIN_SUCCESS object:nil];
    
    [KNotificationCenter addObserver:self selector:@selector(alertTipsView) name:DUE_ALERT object:nil];
    
    if (@available(iOS 10.0, *)) {
        [[UITabBar appearance] setUnselectedItemTintColor:[UIColor cy_colorWithHexString:@"#999999"]];
    } else {
        // Fallback on earlier versions
    }
    self.selectItem = 0; //默认选中第一个
    self.delegate = self;
    [self addChildViewControllers];
}

/// 证件到期提醒条
- (void)alertTipsView {
    for (int i = CJAlertDueTag + 1; i <= CJAlertDueTag + 3; i++) {
        UIView *tipView = [self.view viewWithTag:i];
        tipView ? [tipView removeFromSuperview] : nil;
        tipView ? [self.view setNeedsLayout] : nil;
    }
    [self.view layoutSubviews];
    
    if (!TOKEN_ISEMPTY && !(CarCaptain_Driver)) {
        WEAKSELF
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], PERSONALCENTER_INDEX) withParameter:@{@"token":[UserDefaultUtil valueForKey:USER_TOKEN]} withVC:self netName:@"个人中心初始化" success:^(id response, NSString *msg) {
            /*
            dispatch_async(dispatch_get_main_queue(), ^{
                CGFloat ver = 0;
                if ([response[@"idCardDateHasDue"] boolValue] && !weakSelf.isCloseAlert1) {
                    [NYSTipsView showTipsWithTitle:@"证件到期提醒:"
                                           content:Identity_CarCaptain ? @"车队认证部分证件到期，请及时更新" : @"司机认证部分证件到期，请及时更新"
                                       actionTitle:@"更新"
                                         direction:NYSTipsInDirectionDown
                                  offsetFromCenter:UIOffsetMake(0, ver)
                                          duration:AlertDuration
                                            onView:self.view
                                               tag:CJAlertDueTag+1
                          actionButtonClickedBlock:^{
                        XPRootNavigationController *nav = weakSelf.viewControllers[_selectItem];
                        if (Identity_CarCaptain) {
                            CarTeamAuthVC *ctavc = [[CarTeamAuthVC alloc] init];
                            [nav pushViewController:ctavc animated:YES];
                        } else {
                            DriverAuthVC *davc = [[DriverAuthVC alloc] init];
                            davc.isNotEdit = CarCaptain_Driver ? YES : NO;
                            [nav pushViewController:davc animated:YES];
                        }
                    } closeButtonClickedBlock:^{
                        weakSelf.isCloseAlert1 = YES;
                    }];
                    ver -= 50;
                }
                
                if ([response[@"teamDriverCertificateHasDue"] boolValue] && !weakSelf.isCloseAlert2) {
                    [NYSTipsView showTipsWithTitle:@"证件到期提醒:"
                                           content:@"车队司机证件存在到期，请及时更新"
                                       actionTitle:@"更新"
                                         direction:NYSTipsInDirectionDown
                                  offsetFromCenter:UIOffsetMake(0, ver)
                                          duration:AlertDuration
                                            onView:self.view
                                               tag:CJAlertDueTag+2
                          actionButtonClickedBlock:^{
                        XPRootNavigationController *nav = weakSelf.viewControllers[_selectItem];
                        SiJiManageViewController *sjmvc = [[SiJiManageViewController alloc] init];
                        [nav pushViewController:sjmvc animated:YES];
                    } closeButtonClickedBlock:^{
                        weakSelf.isCloseAlert2 = YES;
                    }];
                    ver -= 50;
                }
                
                if ([response[@"teamVehicleCertificateHasDue"] boolValue] && !weakSelf.isCloseAlert3) {
                    [NYSTipsView showTipsWithTitle:@"证件到期提醒:"
                                           content:@"车队车辆证件存在到期，请及时更新"
                                       actionTitle:@"更新"
                                         direction:NYSTipsInDirectionDown
                                  offsetFromCenter:UIOffsetMake(0, ver)
                                          duration:AlertDuration
                                            onView:self.view
                                               tag:CJAlertDueTag+3
                          actionButtonClickedBlock:^{
                        XPRootNavigationController *nav = weakSelf.viewControllers[_selectItem];
                        VehicleListViewController *vlvc = [[VehicleListViewController alloc] init];
                        vlvc.isCanBindVehicle = 0;
                        [nav pushViewController:vlvc animated:YES];
                    } closeButtonClickedBlock:^{
                        weakSelf.isCloseAlert3 = YES;
                    }];
                }
                [self.view layoutSubviews];
            });
            */
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
    }
}

- (void)logoutEvent {
    UIView *deleView1 = [self.view viewWithTag:CJAlertDueTag+1];
    [deleView1 removeFromSuperview];
    
    UIView *deleView2 = [self.view viewWithTag:CJAlertDueTag+2];
    [deleView2 removeFromSuperview];
    
    UIView *deleView3 = [self.view viewWithTag:CJAlertDueTag+3];
    [deleView3 removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//添加子控制器
- (void)addChildViewControllers{
    //图片大小建议32*32
    [self addChildrenViewController:[[MainViewController alloc] init] andTitle:@"首页" andImageName:@"img_tabbar_home" andSelectImage:@"img_tabbar_home_selected"];
    [self addChildrenViewController:[[HuoYuanViewController alloc] init] andTitle:@"货源" andImageName:@"img_tabbar_huoyuan" andSelectImage:@"img_tabbar_huoyuan_selected"];
    //中间这个不设置东西，只占位
//    [self addChildrenViewController:[[CYInviteViewController alloc] init] andTitle:@"邀请专员" andImageName:@"" andSelectImage:@""];
    [self addChildrenViewController:[[MyViewController alloc] init] andTitle:@"我的" andImageName:@"img_tabbar_my" andSelectImage:@"img_tabbar_my_selected"];
    
}

- (void)addChildrenViewController:(UIViewController *)childVC andTitle:(NSString *)title andImageName:(NSString *)imageName andSelectImage:(NSString *)selectedImage{
    childVC.tabBarItem.image = [[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVC.tabBarItem.selectedImage =  [[UIImage imageNamed:selectedImage] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    childVC.title = title;
    
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    attributes[NSForegroundColorAttributeName] = [UIColor cy_colorWithHexString:@"#999999"];
    [childVC.tabBarItem setTitleTextAttributes:attributes forState:UIControlStateNormal];

    NSMutableDictionary *selectAttri = [NSMutableDictionary dictionary];
    selectAttri[NSForegroundColorAttributeName] = Theme_ColorValue;
    [childVC.tabBarItem setTitleTextAttributes:selectAttri forState:UIControlStateSelected];
//    childVC.tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0,-6, 0);//（当只有图片的时候）需要自动调整
    XPRootNavigationController *baseNav = [[XPRootNavigationController alloc] initWithRootViewController:childVC];
    
    [self addChildViewController:baseNav];
}
//tabbar选择扫车
- (void)buttonAction:(UIButton *)button{
    
    
}

//tabbar选择时的代理
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    self.currentVC = viewController;
    self.selectItem = tabBarController.selectedIndex;
}

// 是否可以点击
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
    
    
    return YES;
}
//旋转动画
- (void)rotationAnimation{
    CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI*2.0];
    rotationAnimation.duration = 3.0;
    rotationAnimation.repeatCount = HUGE;
    [_mcTabbar.centerBtn.layer addAnimation:rotationAnimation forKey:@"key"];
}
@end
